package com.iotp.utils.common;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

public class DataUtil {

    /**
     * 生成MD5密文
     *
     * @param source
     *            明文byte数组
     * @return 密文
     */
    public static String generateMD5(byte[] source) {
        String result = null;
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9','a', 'b', 'c', 'd', 'e', 'f' };
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            md.update(source);
            byte tmp[] = md.digest();
            char str[] = new char[16 * 2];
            int k = 0;
            for (int i = 0; i < 16; i++) {
                byte byte0 = tmp[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            result = new String(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 生成随机密码
     *
     * @param length 密码长度
     * @return String 密码明文
     */
    public static String generatePassword(int length) {
        String val = "";
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            String charOrNum = random.nextInt(2) % 2 == 0 ? "num" : "num";
            if ("char".equalsIgnoreCase(charOrNum)) {
                int choice = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char) (choice + random.nextInt(26));
            } else if ("num".equalsIgnoreCase(charOrNum)) {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }

    /**
     * 生成用户登录Token
     *
     * @param userId
     *            用户Id
     * @return token 登录Token[userId + UUID]
     */
    public static String generateIdentificationCode(String userId) {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        return userId + uuid;
    }

    /**
     * IP地址字符串转换为long型数据
     *
     * @param ip
     *            IP地址字符串
     * @return long long型数据
     */
    public static long ip2long(String ip) {
        long result = 0L;
        try {
            String[] ip_strings = ip.split("\\.");
            if (ip_strings.length != 4) {
                throw new Exception("输入IP地址格式不正确");
            }
            int[] ip_ints = new int[4];
            for (int i = 0; i < 4; i++) {
                ip_ints[i] = Integer.parseInt(ip_strings[i]);
            }
            for (int i = 0; i < 4; i++) {
                result += ip_ints[i] * Math.pow(256, 3 - i);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * long型数据IP地址转换为字符串型IP地址
     *
     * @param ip
     *            型数据IP地址
     * @return String IP地址字符串
     */
    public static String long2ip(long ip) {
        String result = "";
        result += ip % 256;
        ip /= 256;
        result = ip % 256 + "." + result;
        ip /= 256;
        result = ip % 256 + "." + result;
        ip /= 256;
        result = ip % 256 + "." + result;
        return result;
    }

    /**
     * 格式化输出实体
     *
     * @param entity
     *            实体对象
     * @return 格式化字符串
     */
    public static String formatEntity(Object entity) {
        String entityFormat = "";
        Class<? extends Object> cls = entity.getClass();
        Field[] fields = cls.getDeclaredFields();
        for (Field field : fields) {
            if (field.getName().equals("serialVersionUID")) {
                continue;
            }
            char[] buffer = field.getName().toCharArray();
            buffer[0] = Character.toUpperCase(buffer[0]);
            String mothodName = "get" + new String(buffer);
            try {
                Method method = cls.getDeclaredMethod(mothodName);
                Object resutl = method.invoke(entity);
                entityFormat += "\n" + field.getName() + "=>" + resutl;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return entityFormat;
    }

    /**
     * 是否为空（包括：Null和Trim后的空串）
     *
     * @param input
     *            输入字符串
     * @return true-为空 | false-不为空
     */
    public static boolean isEmpty(String input) {
        if (input == null || "".equals(input.trim())) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 是否为空串（单一空串，未Trim）
     *
     * @param input
     *            输入字符串
     * @return true-为空串 | false-不为空串
     */
    public static boolean isBlank(String input) {
        if (input != null && "".equals(input)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 是否为空串（多个空串，已Trim）
     *
     * @param input
     *            输入字符串
     * @return true-为空串 | false-不为空串
     */
    public static boolean isTrimBlank(String input) {
        if (input != null && "".equals(input.trim())) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 时间戳转换成日期格式字符串
     * @param seconds 精确到秒的字符串
     * @param
     * @return
     */
    public static String timeStampToDate(String seconds,String format) {
        if(seconds == null || seconds.isEmpty() || seconds.equals("null")){
            return "";
        }
        if(format == null || format.isEmpty()){
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(Long.valueOf(seconds)));
        //  return  sdf.format(seconds);
    }

    /**
     * getUUID
     * @param type 1：小写   2：大写
     * @return
     */
    public static String getUUID(int type){
        if(type == 1){
            return UUID.randomUUID().toString().replace("-","").toLowerCase();
        }else{
            return UUID.randomUUID().toString().replace("-","").toUpperCase();
        }
    }


    /**
     * 验证字符串长度
     * @param input 输入字符串
     * @param minLength 验证长度-最小长度
     * @param maxLength 验证长度-最大长度
     * @return true-长度合法 | false-长度不合法
     */
    public static boolean validateLength(String input, int minLength, int maxLength) {
        if(input.length() <= maxLength && input.length() >= minLength) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 生成机构编码
     * @param currentMaxOrgCode 当前机构最大编码
     * @param parentOrgCode 父级机构编码
     * @return orgCode
     */
    public static synchronized String getOrgCode(String currentMaxOrgCode, String parentOrgCode) {
        if(currentMaxOrgCode == null || "".equals(currentMaxOrgCode.trim())) {
            if(parentOrgCode == null || "".equals(parentOrgCode.trim())) {
                return "101";
            } else {
                return parentOrgCode + "01";
            }
        } else {
            long currentCodeInt = Long.parseLong(currentMaxOrgCode);
            return "" + (++currentCodeInt);
        }
    }

    /**
     * 生成菜单编码
     * @param currentMaxMenuCode 当前菜单最大编码
     * @param parentMenuCode 父级菜单编码
     * @return menuCode
     */
    public static synchronized String getMenuCode(String currentMaxMenuCode, String parentMenuCode) {
        if(currentMaxMenuCode == null || "".equals(currentMaxMenuCode.trim())) {
            if(parentMenuCode == null || "".equals(parentMenuCode.trim())) {
                return "101";
            } else {
                return parentMenuCode + "01";
            }
        } else {
            long currentCodeInt = Long.parseLong(currentMaxMenuCode);
            return "" + (++currentCodeInt);
        }
    }

    /**
     * 生成用户编码
     * @param currentMaxUserCode 当前用户最大编码
     * @param orgCode 机构编码
     * @return userCode
     */
    public static synchronized String getUserCode(String currentMaxUserCode, String orgCode) {
        if(currentMaxUserCode == null || "".equals(currentMaxUserCode.trim())) {
            return orgCode + "-" + "0000001";
        } else {
            String[] currentMaxUserCodeArray = currentMaxUserCode.split("-");
            long currentCodeInt = Long.parseLong(currentMaxUserCodeArray[1]);
            return orgCode + "-" + String.format("%07d", ++currentCodeInt);
        }
    }

    /**
     * 生成角色编码
     * @param currentMaxRoleCode 当前角色最大编码
     * @param orgCode 机构编码
     * @return roleCode
     */
    public static synchronized String getRoleCode(String currentMaxRoleCode, String orgCode) {
        if(currentMaxRoleCode == null || "".equals(currentMaxRoleCode.trim())) {
            return orgCode + "-" + "001";
        } else {
            String[] currentMaxRoleCodeArray = currentMaxRoleCode.split("-");
            long currentCodeInt = Long.parseLong(currentMaxRoleCodeArray[1]);
            return orgCode + "-" + String.format("%03d", ++currentCodeInt);
        }
    }

    /**
     * 生成权限编码
     * @param currentMaxAuthorityCode 当前权限最大编码
     * @param orgCode 机构编码
     * @return authorityCode
     */
    public static synchronized String getAuthorityCode(String currentMaxAuthorityCode, String parentAuthorityCode, String orgCode) {
        if(currentMaxAuthorityCode == null || "".equals(currentMaxAuthorityCode.trim())) {
            if(parentAuthorityCode == null || "".equals(parentAuthorityCode.trim())) {
                return orgCode + "-" + "001";
            } else {
                return parentAuthorityCode + "01";
            }
        } else {
            String[] currentMaxAuthorityCodeArray = currentMaxAuthorityCode.split("-");
            long currentCodeInt = Long.parseLong(currentMaxAuthorityCodeArray[1]);
            return orgCode + "-" + String.format("%0" + currentMaxAuthorityCodeArray[1].length() + "d", ++currentCodeInt);
        }

    }
}
